const globalIp = getApp().globalData.userIp
const XLSX = require('../../../xlsx.mini.min.js')
var startPoint
var barChart = null;
import * as echarts from '../../../../components/ec-canvas/echarts';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ec: {
      onInit: function (canvas) {
        let pixelRatio = 0
           wx.getSystemInfo({
             success: function(res) {
              pixelRatio = res.pixelRatio
             },
             fail: function () {
               pixelRatio = 0
             }
           })
           barChart = echarts.init(canvas, null, {
             width: 500,
             height: 250,
             devicePixelRatio: pixelRatio
           });
           canvas.setChart(barChart);
           return barChart;
         }
   },
    searchResult:false,
    screen:"条件选择",
    screenDown: {screenDown:["显示销售部门","显示销售员"],screen:0},
    screenFlag: false,//控制综合下拉框是否显示
    screenColor: false,
    dataColor: false,
    dataTime:"日期选择",
    dataTime1:"日期选择",
    dataTime2:"截止日期",
    dataFlag: false, //控制综合下拉框是否显示
    isShowAll:false,
    projectList:[],
    excelList: [],
    openId:'',
    //按钮位置参数
    buttonTop: 0,
    buttonLeft: 0,
    windowHeight: '',
    windowWidth: ''
  },

  exportData() {
    let sheet = []
    this.data.excelList.forEach(item => {
      let row = []
      row.push(item.DocDate)
      row.push(item.销售部门)
      row.push(item.收单量KG)
      row.push(item.已转生产)
      row.push(item.出货KG)
      sheet.push(row)
    });
    // XLSX插件使用
    //自定义列宽
    const colWidth = [
      {
        wch:12
      },
      {
        wch:10
      },
      {
        wch:10
      },
      {
        wch:12
      },
      {
        wch:10
      }
    ]
  
    // XLSX插件使用
    var ws = XLSX.utils.aoa_to_sheet(sheet);
    ws['!cols'] = colWidth
    var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "日收单产出货概况");
    var fileData = XLSX.write(wb, {
      bookType: "xlsx",
      type: 'base64'
    });
    let filePath = `${wx.env.USER_DATA_PATH}/日收单产出货概况.xlsx`
    // 写文件
    const fs = wx.getFileSystemManager()
    fs.writeFile({
      filePath: filePath,
      data: fileData,
      encoding: 'base64',
      success(res) {
        console.log(res,'res1')
        const sysInfo = wx.getSystemInfoSync()
        // 导出
        if (sysInfo.platform.toLowerCase().indexOf('windows') >= 0) {
          // 电脑PC端导出
          wx.saveFileToDisk({
            filePath: filePath,
            success(res) {
              console.log('电脑端打开文档成功！')
            },
            fail(res) {
              console.error(res,'res2')
              util.tips("导出失败")
            }
          })
        } else {
          // 手机端导出
          // 打开文档
          wx.openDocument({
            filePath: filePath,
            //默认为false，true可在右上角进行分享转发
            showMenu:true,
            success: function (res) {
              console.log('手机端打开文档成功！')
            },
            fail: console.error
          })
        }
      },
      fail(res) {
        console.error(res,'res3')
        if (res.errMsg.indexOf('locked')) {
          wx.showModal({
            title: '提示',
            content: '文档已打开，请先关闭',
          })
        }
      }
    })
  },

  showAll(){
    if(this.data.isShowAll){
      this.setData({
        isShowAll:false
      })
    }else{
      this.setData({
        isShowAll:true
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        // 屏幕宽度、高度
        console.log('height=' + res.windowHeight);
        console.log('width=' + res.windowWidth);
        // 高度,宽度 单位为px
        that.setData({
          windowHeight:  res.windowHeight,
          windowWidth:  res.windowWidth,
          buttonTop:res.windowHeight*0.60,//这里定义按钮的初始位置
          buttonLeft:res.windowWidth*0.80,//这里定义按钮的初始位置
        })
      }
    })
    this.setData({
      openId: options.openId
    })
    this.getProject()
  },
  
  //以下是按钮拖动事件
  buttonStart: function (e) {
    startPoint = e.touches[0]//获取拖动开始点
  },
  buttonMove: function (e) {
    var endPoint = e.touches[e.touches.length - 1]//获取拖动结束点
    //计算在X轴上拖动的距离和在Y轴上拖动的距离
    var translateX = endPoint.clientX - startPoint.clientX
    var translateY = endPoint.clientY - startPoint.clientY
    startPoint = endPoint//重置开始位置
    var buttonTop = this.data.buttonTop + translateY
    var buttonLeft = this.data.buttonLeft + translateX
    //判断是移动否超出屏幕
    if (buttonLeft+50 >= this.data.windowWidth){
      buttonLeft = this.data.windowWidth-50;
    }
    if (buttonLeft<=0){
      buttonLeft=0;
    }
    if (buttonTop<=0){
      buttonTop=0
    }
    if (buttonTop + 50 >= this.data.windowHeight){
      buttonTop = this.data.windowHeight-50;
    }
    this.setData({
      buttonTop: buttonTop,
      buttonLeft: buttonLeft
    })
  },
  changeDate1(e) {
    this.setData({
      dataTime1: e.detail.value,
      // dataTime: e.detail.value,
      dataFlag: false,
      dataColor: true
    })
    this.getProject()
  },
  changeDate2(e) {
    this.setData({
      dataTime2: e.detail.value,
      dataFlag: false,
      dataColor: true
    })
    this.getProject()
  },

  dataShow: function () {//日期下拉
    if (this.data.dataFlag){
      this.setData({
        dataFlag : !this.data.dataFlag,
        screenFlag: false,
        screenColor: false
      })
    }else{
      this.setData({
        dataFlag: !this.data.dataFlag,
        screenFlag: false,
        screenColor: false
      })
    }
  },

  screenShow: function () {//综合下拉
    if (this.data.screenFlag){
      this.setData({
        screenFlag : !this.data.screenFlag,
        dataFlag: false,
        dataColor: false
      })
    }else{
      this.setData({
        screenFlag: !this.data.screenFlag,
        dataFlag: false,
        dataColor: false
      })
    }
  },
  screenChoice:function(e){//综合下拉选择子项
    console.log(e)
    this.setData({
      screen: e.currentTarget.dataset.item,
      "screenDown.screen": e.currentTarget.dataset.index,
      screenFlag: false,
      screenColor:true
    })
    this.getProject()
  },
  handletouchtart: function (event) {//点击透明背景隐藏下拉
    this.setData({
      screenFlag: false,
      dataFlag: false
    })
  },
  
  // 统一请求
  getProject(e) {
    let that = this;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: globalIp + 'home/ordr/showProject',
      data: {
        value: that.data.screenDown.screen || 0,
        sdate: that.data.dataTime1 == '日期选择' ? '' : that.data.dataTime1,
        edate: that.data.dataTime2 == '截止日期' ? '' : that.data.dataTime2,
        openId: that.data.openId || wx.getStorageSync('userInfo').openid,
        login: wx.getStorageSync('userInfo').login || 'N'
      },
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      success: function(res) {
        if (res.data.jsonObject) {
          var data = res.data.jsonObject.data;
          var arr = [];
          var ress = [];
          for (var i in data) {
            arr[i] = [];
            for(var j in data[i]) {
              arr[i].push(data[i][j]);
            }
          }
          for (var i = 0; i < arr[0].length; ++i) {
            ress[i] = [];
            for (var j = 0; j < arr.length; ++j) {
              ress[i][j] = arr[j][i];
            }
          }
          that.setData({
            projectList: ress,
            excelList: data
          })
        }
        
        /* 柱状图 */
        var xData = [];
        var sdData = [];
        var yzData = [];
        var chData = [];
        var length = data.length;
        for (var i = 0, j = 1; j < length - 1; i++, j++) {
          xData[i] = data[j].销售部门.substring(0,4);
          sdData[i] = data[j].收单量KG;
          yzData[i] = data[j].已转生产;
          chData[i] = data[j].出货KG;
        }
        barChart.setOption({
          legend: {
            data: ["收单量(t)", "已转生产(t)", "出货(t)"]
          },
          grid: {
            left: "5%",
            right: "5%",
            containLabel: true
          },
          xAxis: {
            data: xData,
            nameLocation: 'middle',
            fontWeight: 'bold'
          },
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: [
            {
              name: "收单量(t)",
              data: sdData,
              type: 'bar'
            },
            {
              name: "已转生产(t)",
              data: yzData,
              type: 'bar'
            },
            {
              name: "出货(t)",
              data: chData,
              type: 'bar'
            }
          ]
        });
        
      },
      fail: function(res) {
        wx.showToast({
          title: '请返回上一页面，重新请求',
          icon: 'none',
          duration: 2000,
        })
      },
      complete: function(res) {
        wx.hideLoading()
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  openPopup() {
    var that = this;
    var tempId = ['xkdLonAAXUGPFkClkk2JB6gJmgJ8wxM2TR7oYHt6yvg'] // 用户同意的消息模板id
    wx.requestSubscribeMessage({   // 调起消息订阅界面
      tmplIds: tempId,
      success (res) {
        console.log(res)
        that.changePushMsg('Y') // 订阅了就后台打勾
        if (res[tempId[0]] === 'accept') {
          // 这里是获取下发权限地方，根据官方文档，可以根据  wx.getSetting() 的 withSubscriptions   这个参数获取用户是否打开订阅消息总开关。后面我们需要获取用户是否同意总是同意消息推送。所以这里要给它设置为true 。
          wx.getSetting({
            withSubscriptions: true,   //  这里设置为true,下面才会返回mainSwitch
            success: function(res){  
              // 调起授权界面弹窗
              if (res.subscriptionsSetting.mainSwitch) {  // 用户打开了订阅消息总开关
                if (res.subscriptionsSetting.itemSettings != null) {   // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
                  let moIdState = res.subscriptionsSetting.itemSettings[tempId];  // 用户同意的消息模板id
                  if (moIdState === 'accept'){   
                    console.log("用户选择了“保持以上选择”")
                    wx.setStorageSync("checkPushFlag",true) // 将总是订阅存入缓存中
                    // that.changePushMsg('Y')
                  }
                }
              } else {
                console.log('订阅消息未开启')
              }      
            }
          })
        }
        else if (res[tempId[0]] === 'reject') {
          console.log('用户拒绝推送')
        }
      },
      fail (err){
        if (err.errCode == 20004) {
          console.log('关闭小程序主开关')
        } else {
          console.log('订阅失败')
        }
      }
    })
  },
  // 改变推送信息状态
  changePushMsg(PushMsg) {
    var msg = PushMsg;
    wx.request({
      url: globalIp + 'home/updateUser',
      data: {
        pushMsg: msg,
        openId: wx.getStorageSync('userInfo').openid
      },
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      success: function(res) {
        console.log(res)
      }
    })
  }
})